package com.vhall.component.framework.common.utils;

import com.vhall.component.framework.common.utils.DebugCollector.Collector;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * debug 容器实例
 *
 * @author xiaoliang.wang@vhall.com
 */
public class DebugCollector extends ThreadLocal<Collector> {

    static class Collector {

        // 存储debug信息
        private final Map<String, Map<String, Object>> collectors = new LinkedHashMap<>();

        @SuppressWarnings("unchecked")
        protected final Collector append(final String fromClass, final String key, final Object value) {
            // fromClass collection
            Map<String, Object> fromClassCollector = collectors.computeIfAbsent(fromClass, k -> new LinkedHashMap<>());
            // key collection
            Object keyCollector = fromClassCollector.get(key);
            if (keyCollector != null) {
                if (keyCollector instanceof ArrayList) {
                    ((ArrayList<Object>) keyCollector).add(value);
                } else {
                    ArrayList<Object> ks = new ArrayList<>(2);
                    ks.add(keyCollector);
                    ks.add(value);
                    fromClassCollector.put(key, ks);
                }
            } else {
                fromClassCollector.put(key, value);
            }
            return this;
        }

        protected Object toObject() {
            return collectors;
        }

    }

    /**
     * 激活 debug 日志容器
     */
    protected void active() {
        set(new Collector());
    }

    /**
     * 获取容器实例本身
     *
     * @return
     */
    protected Object toObject() {
        return get().toObject();
    }
}
